/*
 * This file is part of quickLoad, a software for gamers
 *
 * Copyright (C) 2005-2008 Lucas Romero
 *
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>.
 */
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using ICSharpCode.SharpZipLib.Zip;
using System.Threading;

namespace AutoUpdateInstaller
{
    public partial class Form1 : Form
    {
        private string[] args;
        private string m_ArchivePath = string.Empty;
        private string m_AppDir = string.Empty;
        public Form1(string[] args)
        {
            this.args = args;
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            
        }

        private void StartUpdate()
        {
            UseWaitCursor = true;
            Thread.Sleep(2000);
            UseWaitCursor = false;
            while (Process.GetProcessesByName("quickLoad").Length > 0)
                MessageBox.Show("Please exit all quickLoad instances before updating!" + Environment.NewLine + "There are still " + Process.GetProcessesByName("quickLoad").Length + " processes running!");
            
            
            
            //MessageBox.Show("Update successful!");
           /* System.Diagnostics.Process.Start(
                m_AppDir + Path.DirectorySeparatorChar +
                "AutoUpdateInstaller.exe",
                "\"" + m_upd.DownloadedFile + "\" \"" + Path.GetDirectoryName(Application.ExecutablePath) + "\"");*/
            DirectoryInfo AppDir = new DirectoryInfo(m_AppDir);
            DirectoryInfo BackupDir =
                new DirectoryInfo(Path.GetDirectoryName(m_ArchivePath) + Path.DirectorySeparatorChar + "backup");
            if(!BackupDir.Exists)
                BackupDir.Create();
            if(!AppDir.Exists)
                AppDir.Create();
            ZipInputStream s = null;
            FileStream fs = null;
            try
            {
                s = new ZipInputStream(File.OpenRead(m_ArchivePath));
                ZipEntry theEntry;
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    if(theEntry.IsDirectory || theEntry.Name == "AutoUpdateInstaller.exe")
                        continue;
                    FileInfo fi =
                        new FileInfo(AppDir.FullName + Path.DirectorySeparatorChar +
                                     theEntry.Name.Replace("/", Path.DirectorySeparatorChar.ToString()));
                    if (fi.Exists)
                    {
                        DirectoryInfo d =
                            new DirectoryInfo(Path.GetDirectoryName(BackupDir.FullName + Path.DirectorySeparatorChar +
                                                                    theEntry.Name.Replace("/",
                                                                                          Path.DirectorySeparatorChar.
                                                                                              ToString())));
                        if(!d.Exists)
                            d.Create();
                        fi.CopyTo(BackupDir.FullName + Path.DirectorySeparatorChar +
                                  theEntry.Name.Replace("/", Path.DirectorySeparatorChar.ToString()), true);
                    }
                    if (!fi.Directory.Exists)
                        fi.Directory.Create();
                    fs = new FileStream(fi.FullName, FileMode.Create, FileAccess.Write);
                    int zipbytes;
					const int BLOCK_SIZE = 2048;
					Byte[] zipbuffer = new Byte[BLOCK_SIZE];
                    while((zipbytes = s.Read(zipbuffer,0,zipbuffer.Length)) > 0)
                    {
                        fs.Write(zipbuffer,0,zipbytes);
                        Application.DoEvents();
                    }
                    fs.Close();
                }
                MessageBox.Show("Update successful!");
                System.Diagnostics.Process.Start(m_AppDir + Path.DirectorySeparatorChar +
                                                 "quickLoad.exe");
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
                MessageBox.Show("I will now undo the changes made and reinstall the old version...");
                copyDirectory(BackupDir.FullName,AppDir.FullName);
            }
            finally
            {
                if(s != null)
                    s.Close();
                if(fs != null)
                    fs.Close();
                Application.Exit();
            }
        }
        public static void copyDirectory(string Src,string Dst){
            String[] Files;

            if(Dst[Dst.Length-1]!=Path.DirectorySeparatorChar) 
                Dst+=Path.DirectorySeparatorChar;
            if(!Directory.Exists(Dst)) Directory.CreateDirectory(Dst);
            Files=Directory.GetFileSystemEntries(Src);
            foreach(string Element in Files){
                // Sub directories
                if(Directory.Exists(Element)) 
                    copyDirectory(Element,Dst+Path.GetFileName(Element));
                // Files in directory
                else 
                    File.Copy(Element,Dst+Path.GetFileName(Element),true);
                }
            }

        private void Form1_Shown(object sender, EventArgs e)
        {
            if (args.Length < 2)
            {
                MessageBox.Show("Too few arguments!");
                Application.Exit();
            }
            else
            {
                m_ArchivePath = args[0];
                m_AppDir = args[1];
                if (!File.Exists("ICSharpCode.SharpZipLib.dll"))
                {
                    MessageBox.Show("ZIP library not found, trying to get from application directory '" +
                                    m_AppDir + Path.DirectorySeparatorChar + "ICSharpCode.SharpZipLib.dll'");
                    File.Copy(m_AppDir + Path.DirectorySeparatorChar + "ICSharpCode.SharpZipLib.dll", "ICSharpCode.SharpZipLib.dll");
                }
                StartUpdate();
            }
        }

        
    }
}